import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { Component, OnInit, ViewChild, ElementRef, ChangeDetectorRef } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";

import { ModalController, AlertController, Platform, IonContent } from "@ionic/angular";

import { ActionSheetService, Modal } from "ng-zorro-antd-mobile";

import { EventService } from "src/app/shared/service/event.service";

import { ChooseCityComponent } from "../coms/choose-city/choose-city.component";
import { RankingModalComponent } from "../coms/ranking-modal/ranking-modal.component";
import { SearchComponent } from "../coms/search/search.component";
import { SharePageComponent } from "../coms/share-page/share-page.component";
import { ComItem } from "../route/entry/com-item";
import { AppGlobalService } from "../shared/service/app-global.service";
import { HttpService } from "../shared/service/http.service";
import { MapBaiduService } from "../shared/service/map.baiduapi";
import { TabsService } from "./../shared/service/tabs.service";
declare let Totop;
declare let $: any;
@Component({
  selector: "app-tab3",
  templateUrl: "../route/entry/entry.page.html",
  styleUrls: ["../route/entry/entry.page.scss"],
})
// tslint:disable
export class Tab3Page implements OnInit {
  constructor(
    private http: HttpService,
    private route: ActivatedRoute,
    public router: Router,
    public appGlobalService: AppGlobalService,
    private modalController: ModalController,
    private mapBaiduService: MapBaiduService,
    private dc: ChangeDetectorRef,
    private tabsService: TabsService,
    private eventService: EventService,
    private actionSheet: ActionSheetService, // 必须有
    public alertController: AlertController,
    private pageModalService: PageModalService,
    public platform: Platform
  ) {
    this.eventService.eventEmit.on("appNav", (obj) => {
      this.isFirst = true;
      console.log("app Tabs done");
      this.getViewData(true);
    });
    if (JSON.parse(localStorage.getItem("appNav"))) {
      this.getViewData();
    }
    if (this.eventService.eventEmit.listenerCount('tab3') > 0) {
      this.eventService.eventEmit.removeListener('tab3');
    }
    this.eventService.eventEmit.on("tab3", (obj) => {
      console.log("eventEmit.on tab3");
      this.getViewData();
    });

  }
  headerComs: ComItem[];
  menusBar: any;
  coms: ComItem[];
  subComs: ComItem[];
  footerComs: ComItem[];
  sessionId: string;
  params: any = "";
  // 标签头数据
  titleBar: any;
  isHeader = true;
  isGrayBg = false; // 默认背景为灰色
  bgCssStyle = ''; // 默认背景为灰色
  isPageDisabled = false;
  showRefresher = false;
  showLoading = false;
  backgroundImg: string; // 头部背景图片
  showWaterImg = false;
  showTopTab = false; // 是否显示顶部tab
  showSubTab = false; // 是否显示Subtab
  showEmptyMessage = false; // 是否显示暂无消息
  tagData: any;
  subTagData: any; // 顶部tab data
  switchBlockTag: any; // 蜂喔app新增首页tag样式
  subAWidth: string;
  aWidth: string;
  // 位置对象
  positionInfo: any = {};
  // 小区位置信息
  areaPositionInfo: any = {};
  viewParams: any = {
    sessionId: localStorage.getItem("sessionId"),
    params: { code: JSON.parse(localStorage.getItem("position")).code },
  };
  isFirst = true;
  openBackdrop: boolean;
  showRefresh = false; // 是否显示刷新
  netState: any;
  shareData: any; // 分享页面数据
  isShowTitleBar: any;// 新增是否显示标题栏

  selectedSegment = 0;
  isScrolling = false;
  appTypeCustom: any;
  appTabTypeCustom: any;
  private timer: any;
  tabBarUnderlineStyle: any;
  currentDataArray = [];
  tabPaneIndex = 0;
  isSpinning = false;
  tabPageShowCount = 3;// 默认显示4个
  tabPaneId = 'tab3MainPageTop';
  showScrollToTopBtn = false;// 是否显示滑动到顶部按钮
  isAddCommonNestedTag = true;
  @ViewChild(IonContent) content: IonContent;
  @ViewChild("superCotainer") scrollContent: ElementRef;
  @ViewChild("segment", { read: ElementRef }) private segment: ElementRef;
  serviceLink: any;
  currentRootTabId = new Date().getTime();
  showDivTips = false;
  isHearderDivInConent = false;
  subTagDataId = 'subTagDataId';
  switchNewCssBtnId = 'switchNewCssBtnId';
  ngOnInit() {
    this.subTagDataId += new Date().getTime();
    this.switchNewCssBtnId += new Date().getTime();
    this.openBackdrop = this.appGlobalService.openBackdrop;
    this.positionInfo = JSON.parse(localStorage.getItem("position"));
    const bodyStyles = window.getComputedStyle(document.body);
    this.appTypeCustom = bodyStyles.getPropertyValue('--appTypeCustom').trim().replace('"', '').replace('"', '');
    this.appTabTypeCustom = bodyStyles.getPropertyValue('--appTabTypeCustom').trim().replace('"', '').replace('"', '');
  }

  getViewData(isFirst?) {
    this.route.queryParams.subscribe(
      (p) => {

        if (localStorage.getItem("appNav")) {
          const appNav: any = JSON.parse(localStorage.getItem("appNav"))[2];
          if (
            appNav.params !== undefined &&
            appNav.params.noUseCache !== undefined
          ) {
            this.viewParams.params.noUseCache = appNav.params.noUseCache;
          }
          this.viewParams.viewId = appNav.target;
          if (appNav['type'] !== undefined && appNav['type'] === 'page') {
            return;
          }
        }
        if (this.isFirst || !this.coms || !this.sessionId || this.sessionId !== localStorage.getItem('sessionId')) {
          this.sessionId =  localStorage.getItem('sessionId');
          // 页面空白时 可以再次请求
        } else if (!localStorage.getItem("needRefreshTab3")) {
          // /** 避免重复请求 */
          if (this.appTabTypeCustom === 'LJ') {
            return;
          }
          // return; // 发布类型需要每次都刷新
        }
        this.netWork();
        this.tabPaneIndex = 0;
        localStorage.removeItem("needRefreshTab3");
      },
      (err) => {
        // 第一次请求失败
        if (!this.coms && !this.subComs) {
          if (localStorage.getItem("netState") === "No network connection") {
            this.netState = localStorage.getItem("netState");
          } else {
            this.netState = "";
          }
          this.showRefresh = true;
        }
      }
    );
  }
  netWork() {
    // add by andrew.wen 此处需重新取一次postion 因为页面保存了上一次存的信息
    this.viewParams.sessionId = localStorage.getItem("sessionId");
    this.viewParams.params.code = JSON.parse(
      localStorage.getItem("position")
    ).code;
    this.http.post(
      "application/part/",
      this.viewParams,
      (res) => {
        this.showRefresh = false;
        // 请求数据成功
        if (res) {
          const parseScript = JSON.parse(res.script);
          if (res.script.includes('"style":"payment-order",') || res.script.includes('"style":"tag.MyTagLogic",')) {
            if (parseScript.tags) {
              for (let index = 0; index < parseScript.tags.length; index++) {
                const element = parseScript.tags[index];
                if (element && element.style === 'payment-order') {
                  this.eventService.eventEmit.emit("remindPaymentOrder", element.data);
                } else if (element && element.style === 'tag.MyTagLogic') {
                  if (element.setting
                    && element.setting.link
                    && element.setting.link.params
                    && element.setting.link.params.isShowTitleBar === 'true') {
                    this.isShowTitleBar = element.setting;
                  }
                }
              }
            }
          } else {
            this.eventService.eventEmit.emit("remindPaymentOrder", null);
          }
          // 铺小旺
          if (this.appGlobalService.clientType === "pxw") {
            try {
              if (parseScript.tags.length >= 3 && parseScript.tags[2].style === "invitationMessageTag") {
                const pxwTabObj = this.getPxwTabObj();
                pxwTabObj.currentData.tags = [];
                pxwTabObj.currentData.tags.push(parseScript.tags[2]);
                parseScript.tags[2] = pxwTabObj;
                res.script = JSON.stringify(parseScript);
              }
            } catch (error) {
              console.log("error----->" + JSON.stringify(error));
            }
          }

          // 新增需求 后台如果返回501 则跳转到登录页面
          if (parseScript.code === 501) {
            const params = {
              pageId: parseScript.link.target,
              params: {},
              sessionId: localStorage.getItem("sessionId"),
            };
            this.appGlobalService.goToForward(params);
          } else if (parseScript.code === 502) {
            this.getViewData();
          } else {
            // 先清空 头部标题以及 标题栏 view
            this.coms = null;
            this.tabsService.getPageData(res, (pageData) => {
              this.titleBar = pageData.titleBar;
              if (pageData.coms[0] &&
                pageData.coms[0].tagData.style === "tag.AppTabTagLogic" &&
                pageData.coms[0].tagData.name === "homeAppTabTag") {
                this.tagData = pageData.coms[0].tagData;
                if (document.documentElement.clientWidth >= 375) {
                  this.tabPageShowCount = this.tagData.data.length > 4 ? 4 : this.tagData.data.length;
                } else {
                  this.tabPageShowCount = this.tagData.data.length > 3 ? 3 : this.tagData.data.length;
                }
                // this.aWidth = 100 / this.tagData.data.length + "%";
                this.showTopTab = true;
                this.currentDataArray = new Array(this.tagData.data.length);
                this.currentDataArray[this.tabPaneIndex] = this.tagData.currentData.tags;
                this.tabBarUnderlineStyle = {
                  border: '1px solid #ffca3a',
                  ['border-radius']: ': 0.13rem',
                  bottom: '0rem',
                  background: 'linear-gradient(90deg, #FFE14A 0%, #FFCA3A 100%)',
                  width: '2rem',
                  height: '0.25rem',
                };
                this.tabBarUnderlineStyle['margin-left'] = 'calc(( 100vw / ' + this.tabPageShowCount + '  - 2rem) * 0.5)';
              }
              if (
                pageData.coms[0] &&
                pageData.coms[0].tagData.style === "tag.AppTabTagLogic" &&
                pageData.coms[0].tagData.name === "imagesTag"
              ) {
                this.subComs = pageData.coms;
                // this.coms = undefined;
                this.showSubTab = true;
                this.showTopTab = false;
                this.subTagData = this.subComs[0].tagData;
                if (this.subTagData) {
                  // this.subTagData.currentTab = 1;
                  if (document.documentElement.clientWidth >= 375) {
                    this.tabPageShowCount = this.subTagData.data.length > 4 ? 4 : this.subTagData.data.length;
                  } else {
                    this.tabPageShowCount = this.subTagData.data.length > 3 ? 3 : this.subTagData.data.length;
                  }
                  this.currentDataArray = new Array(this.subTagData.data.length);
                  this.currentDataArray[this.tabPaneIndex] = this.subTagData.currentData.tags;
                  // this.tabBarUnderlineStyle = { border: '1px solid #ffca3a', bottom: '4px', background: '#0A3CA0', width: '2rem' };
                  this.tabBarUnderlineStyle = {
                    border: '1px solid #ffca3a',
                    ['border-radius']: '0.13rem',
                    bottom: '0rem',
                    background: 'linear-gradient(90deg, #FFE14A 0%, #FFCA3A 100%)',
                    width: '2rem',
                    height: '0.25rem'
                  };
                  this.tabBarUnderlineStyle['margin-left'] = 'calc(( 100vw / ' + this.tabPageShowCount + '  - 2rem) * 0.5)';
                }



              } else {
                this.showSubTab = false;
              }

              this.coms = pageData.coms;
              this.headerComs = pageData.headerComs;
              // 蜂喔APP以及蜂喔商户APP新增消息为空暂时暂无消息
              if (this.appTabTypeCustom === 'LJ' && this.coms.length === 0) {
                this.showEmptyMessage = true;
              } else {
                this.showEmptyMessage = false;
              }
              if (this.isShowTitleBar !== undefined) {
                this.titleBar = {};
                // bgImgStyle
                if (this.isShowTitleBar.link && this.isShowTitleBar.link.params && this.isShowTitleBar.link.params.toolbarCssStyle) {
                  this.titleBar['bgImgStyle'] = this.isShowTitleBar.link.params.toolbarCssStyle;
                }
                // link
                if (this.isShowTitleBar.link && this.isShowTitleBar.link.params) {
                  this.titleBar['link'] = this.isShowTitleBar.link;
                }
                // 1.6.34 新增参数
                if (pageData.titleBar && pageData.titleBar.cssStyle !== undefined) {
                  this.titleBar['cssStyle'] = pageData.titleBar.cssStyle;
                }

                // 1.6.34 新增参数
                if (this.isShowTitleBar.link && this.isShowTitleBar.link.params && this.isShowTitleBar.link.params.headerStyle) {
                  this.titleBar['headerStyle'] = this.isShowTitleBar.link.params.headerStyle;
                }

              }
              this.footerComs = pageData.footerComs;
              this.isGrayBg = pageData.isGrayBg;
              this.bgCssStyle = pageData.bgCssStyle;
              this.isPageDisabled = pageData.disabled;
              this.showRefresher = pageData.showRefresher;
              this.showLoading = pageData.showLoading;
              this.backgroundImg = pageData.backgroundImg;
              this.showWaterImg = pageData.showWaterImg;
              this.isFirst = false;
              this.getCurrentToggleData();
              console.log('this.currentRootTabId', this.currentRootTabId);

              setTimeout(() => {
                if (document.getElementById('superToolbar' + this.currentRootTabId)) {
                  try {
                    document.getElementById('superToolbar' + this.currentRootTabId).setAttribute("style", this.titleBar.cssStyle);
                  } catch (error) {

                  }
                }
              }, 100);
              this.appGlobalService.refreshViewTree(this.content);

            });
          }
        } else {
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, "middle");
        }
      },
      (err) => {
        // 第一次请求失败
        if (!this.coms && !this.subComs) {
          if (localStorage.getItem("netState") === "No network connection") {
            this.netState = localStorage.getItem("netState");
          } else {
            this.netState = "";
          }
          this.showRefresh = true;
        }
      }
    );
  }
  buttonClick(obj) {
    if (obj.type === "page") {
      const params = {
        pageId: obj.target,
        params: {},
        sessionId: localStorage.getItem("sessionId"),
      };
      if (obj.param) {
        params.params = { code: this.positionInfo.code };
      }
      this.appGlobalService.goToForward(params);
    } else if (obj.type === "modal") {
      this.showCityModel(obj.target);
    }
  }
  onTabsChange(i, item, currentData?) {
    this.http.delayShowLoading();
    this.isSpinning = true;
    this.tabPaneIndex = i.index;
    const mViewId = item[i.index].partLink.target;
    const mParams = item[i.index].partLink.params;

    this.http.post('application/part',
      {
        viewId: mViewId,
        sessionId: localStorage.getItem("sessionId"),
        params: mParams,
        tagOrder: 0
      }, (res: any) => {
        // setTimeout(() => {
        const tmpData = JSON.parse(res.script);
        this.tagData.currentData.tags = tmpData.tags;
        this.currentDataArray[this.tabPaneIndex] = tmpData.tags;
        this.isSpinning = false;
        // }, 200);
      });

  }

  async showCityModel(target) {
    const that = this;
    const modal = await this.modalController.create({
      component: ChooseCityComponent,
      componentProps: { value: target, type: 1, modalTitle: "选择城市" }, //    首页是1 默认不传或者0
    });
    modal.onDidDismiss().then(() => {
      that.positionInfo = JSON.parse(localStorage.getItem("position"));
      that.sessionId = localStorage.getItem("sessionId");
      that.viewParams.params.code = that.positionInfo.code;
      that.viewParams.sessionId = that.sessionId;
      // 切换完城市后需要刷新tab1-3
      localStorage.setItem("needRefreshTab1", "true");
      localStorage.setItem("needRefreshTab2", "true");
      localStorage.setItem("needRefreshTab3", "true");
      localStorage.setItem("needRefreshTab4", "true");
      localStorage.setItem("needRefreshTab5", "true");
      that.netWork();
    });
    return await modal.present();
  }

  searchButtonClick(obj) {
    console.log("to search history");
    localStorage.removeItem("searchParams");
    const searchPath = "/navSearch";
    this.router.navigate([searchPath], {
      queryParams: { obj: JSON.stringify(obj) },
    });
  }

  /**
   * 返回方法
   */
  back() {
    this.appGlobalService.goBack();
  }
  close() {
    this.appGlobalService.goBack();
  }
  /** 收藏 */
  favorite(submit) {
    // 判断是否登录 登录 返回 详情
    const params = {
      id: submit.id,
      content: submit.content,
      sessionId: localStorage.getItem("sessionId"),
    };

    console.log("favorite --> submit", params);
    this.http.post("application/submit", params, (res) => {
      // 请求成功
      if (res.success) {
        // 更新收藏icon UI
        if (this.titleBar.favorite.icon === "unfavorite") {
          this.titleBar.favorite.icon = "favorite";
        } else {
          this.titleBar.favorite.icon = "unfavorite";
        }
        console.log("favorite -->", res.message);
      } else {
        // 请求数据失败
        this.appGlobalService.showToast(res.message, 2000, "middle");
        if (res.type === "page") {
          this.pageModalService.openPage({ type: 'page', target: res.target, params: res.params ? res.params : {} })
        }
      }
    });
  }

  // 分享弹框
  async presentModal() {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: "sharePage",
      backdropDismiss: true,
      component: SharePageComponent,
      componentProps: { tagData: this.shareData },
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData);
  }

  /** 分享 */
  share(link) {
    console.log("share --> page", link);
    // 请求参数
    const params = {
      sessionId: localStorage.getItem("sessionId"),
      pageId: link.target,
      params: link.params,
    };
    this.http.post("application/page", params, (res) => {
      console.log(JSON.parse(res.script));
      this.shareData = JSON.parse(res.script).views[0].tags[0].data;
      console.log(this.shareData);
      this.presentModal();
    });
  }

  subChange(obj, indexTab) {
    if (obj !== undefined && obj.partLink !== undefined) {
      this.subTagData.currentTab = indexTab;
      this.appGlobalService.lastMessageIndex = indexTab;
      this.http.post(
        "application/part",
        {
          viewId: obj.partLink.target,
          sessionId: localStorage.getItem("sessionId"),
          params: obj.partLink.params,
        },
        (res: any) => {
          if (res !== undefined && res != null) {
            setTimeout(() => {
              this.subTagData.currentData = JSON.parse(res.script);
              // localStorage.setItem("refreshGrayBgTag", "" + this.subTagData.currentData.isGrayBg);
              // this.eventService.eventEmit.emit("refreshGrayBg", "refreshGrayBg");
              localStorage.setItem("dataMapFixedTabContainer", JSON.stringify(this.subTagData));
              this.eventService.eventEmit.emit("refreshTab3FixedContainer", "refreshTab3FixedContainer");
            }, 0);
          }
        }
      );
    }
  }

  // 聊天
  chat(chat) {
    if (chat.link && chat.link.type === "chat") {
      const cityId = JSON.parse(localStorage.getItem("position"))
        ? JSON.parse(localStorage.getItem("position")).code
        : 4403;
      const ifLogin = localStorage.getItem("userId") !== "null";
      if (ifLogin) {
        this.http.getImId(
          chat.link.params.opportunity_id,
          chat.link.params.customer_id,
          cityId,
          (item) => {
            this.router.navigate(["chatOnline"], {
              queryParams: { item: JSON.stringify(item) },
            });
          }
        );
      }
    }
  }
  // 更多
  moreLine(more) {
    const that = this;
    const buttons: any = [];
    more.data.forEach((element, index) => {
      buttons.push(element.label);
    });
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        maskClosable: true,
      },
      (buttonIndex) => {
        if (buttonIndex > -1) {
          console.log(more.data[buttonIndex]);
          that.selectItem(more.data[buttonIndex]);
        }
      }
    );
  }
  selectItem(item) {
    if (item.action === "submit") {
      item.submit.sessionId = localStorage.getItem("sessionId");
      console.log("more --> submit", item.submit);
      this.http.post("application/submit", item.submit, (res) => {
        this.appGlobalService.showToast(res.message, 2000, "middle");
      });
    } else if (item.action === "link") {
      const param = {
        pageId: item.link.target,
        params: item.link.params ? item.link.params : {},
        sessionId: localStorage.getItem("sessionId"),
      };
      this.appGlobalService.goToForward(param);
    } else if (item.action === "question") {
      // alert
      this.question(item);
    } else if (item.action === "prompt") {
      // 弹出输入框 alert
      this.inputAlert(item);
    } else if (item.action === "modal") {
      this.openRankingModal("ranking-modal", item);
    } else if (item.action === "view") {
      const param = {
        viewId: item.link.target,
        params: item.link.params ? item.link.params : {},
        sessionId: localStorage.getItem("sessionId"),
      };
      this.appGlobalService.goToForward(param);
    } else if (item.action = 'share') {
      this.share(item.link);
    }
  }
  // ranking-modal
  async openRankingModal(className, item) {
    const params = {
      sessionId: localStorage.getItem("sessionId"),
      pageId: item.link.target,
      params: item.link.params,
    };
    this.http.post("application/page", params, async (res) => {
      const tagData = JSON.parse(res.script).views[0].tags[0].data;
      // "ranking-modal"
      const modal = await this.modalController.create({
        showBackdrop: true,
        cssClass: className,
        component: RankingModalComponent,
        componentProps: { tagData },
      });
      await modal.present();
      // 监听销毁的事件
      const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    });
  }
  // alert
  async question(item) {
    const alert = await this.alertController.create({
      header: "",
      subHeader: "",
      message: item.question,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary",
          handler: (blah) => {
            console.log("取消");
          },
        },
        {
          text: "确定",
          handler: () => {
            item.submit.sessionId = localStorage.getItem("sessionId");
            console.log("more --> submit", item.submit);
            this.http.post("application/submit", item.submit, (res) => {
              this.appGlobalService.showToast(res.message, 2000, "middle");
            });
          },
        },
      ],
    });
    await alert.present();
  }

  inputAlert(item) {
    const that = this;
    Modal.prompt(
      item.htmlObj.title,
      "",
      [
        {
          text: item.htmlObj.buttonLabel,
          onPress: (value) =>
            new Promise((resolve, reject) => {
              if (value.length === 0 || that.appGlobalService.isPhone(value)) {
                resolve();
                item.submit.content[item.htmlObj.input.formKey] = value;
                item.submit.sessionId = localStorage.getItem("sessionId");
                console.log("more --> submit", item.submit);
                that.http.post("application/submit", item.submit, (res) => {
                  // 请求成功
                  if (res.message) {
                    this.appGlobalService.showToast(
                      res.message,
                      2000,
                      "middle"
                    );
                  }
                });
              } else {
                that.appGlobalService.showToast(
                  "请输入正确的号码",
                  2000,
                  "top"
                );
              }
            }),
        },
      ],
      "default",
      null,
      [item.htmlObj.input.placeholder]
    );
  }
  //
  filter(filter) {
    const param = {
      pageId: filter.link.target,
      params: filter.link.params ? filter.link.params : {},
      sessionId: localStorage.getItem("sessionId"),
    };
    this.appGlobalService.goToForward(param);
  }

  // 确定提交表单用 暂时没用
  textButton(textButton) {
    // console.log(textButton);
    if (textButton !== undefined && textButton.link !== undefined) {
      // this.appGlobalService.openPage
      this.pageModalService.openPage(textButton.link);
    } else if (textButton !== undefined && textButton.submit !== undefined) {
      textButton.submit['sessionId'] = localStorage.getItem('sessionId');
      // 1.8.2 新增submit
      this.http.post('application/submit', textButton.submit, res => {
        this.appGlobalService.showToast(res.message, 2000, 'middle');
        this.getViewData();
      });
    }
  }
  // 数组btn
  iconButtonClick(item) {
    this.selectItem(item);
  }

  toggle(toggleButton, index) {
    if (toggleButton[index].checked) {
      return;
    } else if (index === 0) {
      toggleButton[0].checked = true;
      toggleButton[1].checked = false;
      this.toggleChange(toggleButton[0], "0");
    } else {
      toggleButton[0].checked = false;
      toggleButton[1].checked = true;
      toggleButton[1].hasNew = false;
      this.toggleChange(toggleButton[1], "1");
    }
  }

  getCurrentToggleData() {
    if (this.titleBar && this.titleBar.toggleButton) {
      this.titleBar.toggleButton.forEach((e, i) => {
        if (e.checked) {
          this.toggleChange(e, i.toString());
        }
      });
    }
  }

  toggleChange(obj, index?) {
    if (obj !== undefined && obj.partLink !== undefined) {
      this.http.post(
        "application/part",
        {
          viewId: obj.partLink.target,
          sessionId: localStorage.getItem("sessionId"),
          params: obj.partLink.params,
        },
        (res: any) => {
          if (res !== undefined && res != null) {
            this.tabsService.getPageData(res, (pageData) => {
              this.coms = pageData.coms;
              this.footerComs = pageData.footerComs;
            });
          }
        }
      );
    }
  }
  scrollEnd(e: any) {
    this.isScrolling = false;
    e.preventDefault();
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      if (this.appGlobalService.topTop) {
        this.appGlobalService.topTop = false;
        this.content.scrollToTop(200);
      }
    }, 300);
  }
  onScroll(e: any,titleBar?) {  
    this.isScrolling = true;
    let that = this;
    e.preventDefault();
    if (titleBar && titleBar.onScroll === 'false') {
      // 不处理onScroll内逻辑
      // <!-- 页面title设置 2023年11月8日新增onScroll="false" 返回字符串“false” 表示前端页面不处理滑动事件； 不配置不返回属性  -->
      return;
    }
    // 导航全透明滑动变化
    //     <!-- titleBar 增加属性  headerId  、customBgStyle， customBg（要支持富文本），
    // 滑动前样式原有headerStyle，background （作用于toolbar),  新增 toolbarStyle 
    // 滑动后要改变样式用到：新增： headerChangeStyle ,toolbarChangeStyle
    // 共新增 6个属性  -->
    if (this.titleBar && this.titleBar.headerId && document.getElementById('home-header-bg-box' + this.titleBar.headerId) && this.titleBar.fullscreen ) {
      this.content.ionScroll.subscribe(($event: any) => {
        
        const ionHeader = document.getElementById('home-header-bg-box' + this.titleBar.headerId) as HTMLElement;
        const ionToolbar = document.getElementById('superToolbar' + this.currentRootTabId) as HTMLElement;
        if ($event.detail.scrollTop > 64 && !that.isHearderDivInConent) {
          console.log('onScroll:__fullscreen' + $event.detail.scrollTop);
          that.isHearderDivInConent = true;
          try {
            if (this.titleBar.headerChangeStyle && this.titleBar.toolbarChangeStyle) {
              ionHeader.setAttribute("style", this.titleBar.headerChangeStyle);
              ionToolbar.setAttribute("style", this.titleBar.toolbarChangeStyle);
              

            } else {
              ionHeader.setAttribute("style", "background:white;position:fixed;z-index: 10000;");
              ionToolbar.setAttribute("style", "--background:white;padding-top:constant(safe-area-inset-top)");
              
            }
            // title
            if (ionToolbar.children && ionToolbar.children.length > 0 && this.titleBar.title ) {
              const that = this;
              $("#"+'superToolbar' + this.currentRootTabId).children().each(function(i, e) {
                
                if (e.id == "nav-title"){
                  if (that.titleBar.title.changeCssStyle){
                    e.setAttribute("style", that.titleBar.title.changeCssStyle);
                  } else {
                    // e.setAttribute("style", "font-size: 1.13rem;font-weight: bold;padding: unset !important;color: #0f0f0f;");
                  }
                  

                }    
                });
                
            }

          } catch (error) {

          }
        } else if ($event.detail.scrollTop <= 64 && that.isHearderDivInConent){
          try {
            that.isHearderDivInConent = false;
            if (this.titleBar.headerStyle && this.titleBar.toolbarStyle) {
              ionHeader.setAttribute("style", this.titleBar.headerStyle);
              ionToolbar.setAttribute("style", this.titleBar.toolbarStyle);
              
            } else {
              ionHeader.setAttribute("style", "background:transparent;position:fixed;z-index: 10000;backdrop-filter:unset;");
              ionToolbar.setAttribute("style", "--background:transparent;padding-top:constant(safe-area-inset-top)");
    
            }
            // title
            if (ionToolbar.children && ionToolbar.children.length > 0 && this.titleBar.title ) {
              const that = this;
              $("#"+'superToolbar' + this.currentRootTabId).children().each(function(i, e) {
                
                if (e.id == "nav-title"){
                  if (that.titleBar.title.cssStyle){
                    e.setAttribute("style", that.titleBar.title.cssStyle);
                  } else {
                    // e.setAttribute("style", "font-size: 1.13rem;font-weight: bold;padding: unset !important;color: transparent;");
                  }
                }    
                });
              }

          } catch (error) {

          }
        }
      })

    }
  }
  // 点击遮罩层关闭下拉面板
  backdropclick() {
    this.openBackdrop = false;
  }

  async segmentChanged(e: any) {
    const index = e.detail.value;
    this.selectedSegment = index;
    const segmentButton = this.segment.nativeElement.children[index];
    segmentButton.scrollIntoView({
      behavior: "smooth",
      inline: "center",
      block: "nearest",
    });
    if (this.tagData.data) {
      this.tagData.currentTab = index;
      // 删除表单信息
      // update by andrew.wen for 之前首页缓存了 铺铺旺的topTap现在改成蜂喔不使用改标签缓存了。
      // if (localStorage.getItem("topTapPart" + index)) {
      //   const parseData = JSON.parse(
      //     localStorage.getItem("topTapPart" + index)
      //   );
      //   this.tagData.currentData = parseData;
      //   localStorage.setItem(
      //     "refreshGrayBgTag",
      //     "" + this.tagData.currentData.isGrayBg
      //   );
      //   this.eventService.eventEmit.emit("refreshGrayBg", "refreshGrayBg");
      //   setTimeout(() => {
      //     localStorage.setItem(
      //       "dataMapTopTabContainer",
      //       JSON.stringify(this.tagData)
      //     );
      //     this.eventService.eventEmit.emit(
      //       "refreshTopTabContainer",
      //       "refreshTopTabContainer"
      //     );
      //     this.content.scrollToTop(0);
      //   }, 200);
      // } else {
      this.http.post(
        "application/part",
        {
          viewId: this.tagData.data[index].partLink.target,
          sessionId: localStorage.getItem("sessionId"),
          params: this.tagData.data[index].partLink.params,
        },
        (res: any) => {
          // #616 修改：点击转让服务和选址服务跳到第一屏的画面
          this.content.scrollToTop(0);
          if (res !== undefined && res != null) {
            const switchData = JSON.parse(res.script);
            if (switchData.tags.length > 0 && switchData.tags[0].style === 'tag.AppGeneralFormTagLogic') {
              const paramName = switchData.tags[0].paramName;
              // 如果包含 tag.AppGeneralFormTagLogic 则清除 form表单
              this.appGlobalService.delFormGroupWithParamName(paramName);
            }
            setTimeout(() => {
              this.tagData.currentData = switchData;
              localStorage.setItem("refreshGrayBgTag", "" + this.tagData.currentData.isGrayBg);
              this.eventService.eventEmit.emit("refreshGrayBg", "refreshGrayBg");
              localStorage.setItem("dataMapTopTabContainer", JSON.stringify(this.tagData));
              this.eventService.eventEmit.emit("refreshTopTabContainer", "refreshTopTabContainer");
            }, 50);
          }
        }
      );
      // }
    }
  }

  async customSegmentChanged(e: any) { }
  getPxwTabObj() {
    return {
      type: "tag",
      style: "tag.AppTabTagLogic",
      name: "pxwNavMsgTabTag",
      linearLayout: "body",
      currentTab: "0",
      isShowLine: false,
      isCustomerTag: true,
      isRefreshByOtherTag: "1",
      data: [
        {
          badge: "0",
          partLink: {
            type: "view",
            params: {
              noUseCache: "true",
            },
            target: "45276",
          },
          indexTab: "0",
          tabType: "dafault",
          label: "系统消息",
        },
        {
          badge: "0",
          partLink: {
            type: "page",
            params: {},
            target: "45277",
          },
          indexTab: "1",
          tabType: "invite",
          label: "邀约聊天",
        },
      ],
      currentData: {
        type: "view",
        style: "view.DefaultViewLogic",
        name: null,
        isGrayBg: false,
        showWaterImg: false,
        tags: [],
      },
      scroll: false,
    };
  }

  refreshData(event) {
    event.target.complete();
  }

  loadData(event) {
    setTimeout(() => {
      event.target.complete();
    }, 500);
  }
  ionViewWillEnter() {
    // localStorage.setItem("needRefreshTab3", "false");
    // localStorage.setItem("needRefresh", "false");
    if (this.eventService.eventEmit.listenerCount('TOTOP') > 0) {
      this.eventService.eventEmit.removeListener('TOTOP');
    }
    this.eventService.eventEmit.on("TOTOP", (obj) => {
      // console.log("TOTOP tab3");
      if (this.isScrolling) {
      } else {
        this.appGlobalService.topTop = false;
        this.content.scrollToTop(200);
      }
    });
    if (this.tagData && this.tagData.currentTab) {
      this.tagData.currentTab = '0';
    }
    // this.tagData.currentTab = '0';
  }

  ionViewWillLeave() {
    if (this.appTypeCustom === 'LJ') {
      if (this.appTabTypeCustom !== 'LJ') {
        this.netWork();
      }
    }
  }

  ngAfterViewChecked(): void {
    // let currentTabStr = 'hometopSegmentBtn';
    // if (this.tagData && this.tagData.currentTab) {
    //   if (this.tagData.currentTab) {
    //     currentTabStr += this.tagData.currentTab;
    //   } else {
    //     currentTabStr += '0';
    //   }
    //   if (this.tagData.currentTab === '0') {
    //     if (document.getElementById('hometopSegmentBtn1') && this.hasClass(document.getElementById('hometopSegmentBtn1'), 'segment-button-checked')) {
    //       return;
    //     } else if (document.getElementById(currentTabStr) && !this.hasClass(document.getElementById(currentTabStr), 'segment-button-checked')) {
    //       document.getElementById(currentTabStr).click();
    //     } else {
    //       document.getElementById(currentTabStr).click();
    //     }
    //   }
    //   if (this.appTypeCustom !== "LJ") {
    //     if (document.getElementById(currentTabStr)) {
    //       const firstBtn = document.getElementById(currentTabStr);
    //       firstBtn.click();
    //     }
    //   }
    // }
  }
  hasClass(ele, value) {
    let has = false;
    if (value) {
      const curValue = this.getClass(ele);
      if (curValue.indexOf(value) > -1) {
        has = true;
      }
    }
    return has;
  }
  getClass(elem) {
    return elem.getAttribute && elem.getAttribute("class") || "";
  }

  switchBlockClick(item, className) { }
  // 滑动到顶部 
  scrollToTop(event) {
    if (event) {
      event.stopPropagation();
    }
    this.content.scrollToTop(1000);
  }
  gotoEnterpriseWechat(e) { }
  showTipBox(type) {
    this.appGlobalService.showTipBox(type);
  }
  changeCity(item, event?) {
    if (event !== undefined) {
      event.stopPropagation();
    }
  }
}
